package com.zz.hhbl.ui.ai

import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.ss.bytertc.engine.RTCRoom
import com.ss.bytertc.engine.RTCRoomConfig
import com.ss.bytertc.engine.RTCVideo
import com.ss.bytertc.engine.UserInfo
import com.ss.bytertc.engine.handler.IRTCRoomEventHandler
import com.ss.bytertc.engine.handler.IRTCVideoEventHandler
import com.ss.bytertc.engine.type.ChannelProfile
import com.zz.framework.core.base.BaseActivity
import com.zz.framework.core.ext.fromJson
import com.zz.framework.core.ext.toUtf8String
import com.zz.framework.core.utils.DeviceUtils
import com.zz.framework.core.utils.LogUtils
import com.zz.framework.core.utils.MediaPlayerUtils
import com.zz.framework.core.utils.ZCountDownTimer
import com.zz.framework.core.utils.language.LanguageManager
import com.zz.hhbl.config.GlobalCache
import com.zz.hhbl.entity.AiMessageEntity
import com.zz.hhbl.entity.AiSubtitleEntity
import com.zz.hhbl.ui.CommonViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.nio.ByteBuffer

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/7 21:28.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
abstract class BaseAiActivity: BaseActivity() {
    internal val viewModel: CommonViewModel by viewModels()
    private var rtcVideo: RTCVideo? = null
    protected var rtcRoom: RTCRoom? = null
    var roomId = GlobalCache.getAiConfig().roomId.orEmpty()
    var userId = GlobalCache.getAiConfig().userId.orEmpty()
    var token = GlobalCache.getAiConfig().token.orEmpty()
    var appId = GlobalCache.getAiConfig().appId.orEmpty()
    var isLeave = false
    val timerTime = 5*60*1000L
    /**
     * 音色
     * @return String
     */
    open fun getToneType():String{
        return "BV005_streaming"
    }

    /**
     * 智能体类型，对话或者翻译
     * @return String
     */
    open fun getAiType():String{
        return "dialogueAI"
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        requestPermission()
    }

    protected fun startVoiceChat() {
        viewModel.startVoiceChat(
            hashMapOf(
                "chatType" to getAiType(),
                "voiceType" to getToneType(),
                "lang" to LanguageManager.currentLangCode,
                "deviceNumber" to DeviceUtils.getSerialCode()
            )
        )
    }

    /**
     * @param handleType Int 1.打断 2.重播语音
     * @param playText String  操作类型为2时必传
     */
    fun updateVoiceChat(handleType:Int = 1 ,playText:String = "") {
        viewModel.updateVoiceChat(
            hashMapOf(
                "handleType" to handleType,
                "playText" to playText,
                "deviceNumber" to DeviceUtils.getSerialCode()
            )
        )
    }

    override fun initObserver() {
        viewModel.stopVoiceChatLiveData.observe(this) {
            finish()
        }
        viewModel.getChatTokenConfigLiveData.observe(this) {
            //新进入房间
            joinRoom(roomId, userId)
        }
    }
    //5分钟
    val timer = object : ZCountDownTimer(timerTime,1000) {
        override fun onTick(millisUntilFinished: Long) {

        }
        override fun onFinish() {
            //倒计时结束
            onTimerFinish()
        }
    }

    open fun onTimerFinish(){

    }

    private fun requestPermission() {
        XXPermissions.with(this).permission(Permission.RECORD_AUDIO, Permission.CAMERA).request { permissions, allGranted ->
            run {
                if (allGranted) {
                    rtcVideo = RTCVideo.createRTCVideo(this, appId, videoEventHandler, null, null)
                    rtcVideo?.startAudioCapture()
                    joinRoom(roomId, userId)
                    startVoiceChat()
                } else {

                }
            }
        }
    }

    /**
     * 引擎回调信息
     */
    var videoEventHandler: IRTCVideoEventHandler = object : IRTCVideoEventHandler() {
        override fun onError(err: Int) {
            super.onError(err)
            LogUtils.error("err:$err")
        }
        //https://www.volcengine.com/docs/6348/70081#IRTCVideoEventHandler-onseimessagereceived
        override fun onUserMessageReceivedOutsideRoom(uid: String?, message: String?) {
            super.onUserMessageReceivedOutsideRoom(uid, message)
            LogUtils.error("message:$message")
        }
        //发送消息，发送方收到的回执
        override fun onUserMessageSendResultOutsideRoom(msgid: Long, error: Int) {
            super.onUserMessageSendResultOutsideRoom(msgid, error)
        }
    }

    private var rtcRoomEventHandler: IRTCRoomEventHandler = object : IRTCRoomEventHandler() {
        //消息发送结果
        override fun onRoomMessageSendResult(msgid: Long, error: Int) {
            super.onRoomMessageSendResult(msgid, error)
            timer.restart()
        }

        //接收到的二进制消息
        override fun onRoomBinaryMessageReceived(uid: String?, message: ByteBuffer) {
            super.onRoomBinaryMessageReceived(uid, message)
            val json = splitJsonString("${message.toUtf8String()}")
            val entity = json.fromJson<AiMessageEntity>()
            //LogUtils.error("===> json:${entity.toJson()}")
            entity.data?.firstOrNull()?.let {
                lifecycleScope.launch(Dispatchers.Main) {
                     onMessageReceived(it)
                }
                LogUtils.error("message ===>userId:${userId} text:${it.text}   paragraph:${it.paragraph}    definite:${it.definite}    ")
            }
            timer.restart()
        }


        override fun onTokenWillExpire() {
            super.onTokenWillExpire()
            //重新更新token配置
            viewModel.getChatTokenConfig()
        }
    }

    abstract fun onMessageReceived(message:AiSubtitleEntity)

    private fun splitJsonString(message: String): String {
        val jsonStartIndex = message.indexOf('{')
        val jsonString = if (jsonStartIndex != -1) {
            message.substring(jsonStartIndex) // 截取 JSON 部分
        } else {
            "{}"
        }
        return jsonString
    }

    /**
     * 加入房间
     * @param roomId
     */
    protected fun joinRoom(roomId: String, userId: String) {
        rtcRoom = rtcVideo?.createRTCRoom(roomId)
        rtcRoom?.setRTCRoomEventHandler(rtcRoomEventHandler)
        //0: 静音  100 原始大小  400 4倍
        rtcRoom?.setRemoteRoomAudioPlaybackVolume(100)
        // 用户信息
        val userInfo = UserInfo(userId, """{"tsFlag":13222,"UserExtraInfo":1}""")
        // 设置房间配置
        val isAutoPublish = true
        val isAutoSubscribeAudio = true
        val isAutoSubscribeVideo = false
        val roomConfig = RTCRoomConfig(ChannelProfile.CHANNEL_PROFILE_COMMUNICATION, isAutoPublish, isAutoSubscribeAudio, isAutoSubscribeVideo)
        // 加入房间
        rtcRoom?.joinRoom(token, userInfo, roomConfig)
    }

    /**
     * 离开房间
     */
    protected fun leaveRoom() {
        rtcRoom?.leaveRoom()
        rtcRoom?.destroy()
        rtcRoom = null
    }

    override fun onStop() {
        super.onStop()
        leaveRoom()
        stopVoiceChat()
        rtcVideo?.stopVideoCapture()
        rtcVideo?.stopAudioCapture()
        RTCVideo.destroyRTCVideo()
        //取消定时
        timer.cancel()
    }


    override fun onDestroy() {
        super.onDestroy()
    }

    protected fun stopVoiceChat() {
        viewModel.stopVoiceChat()
    }
}